package com.jzo2o.market.job;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.jzo2o.market.constants.RedisConstants;
import com.jzo2o.market.enums.ActivityStatusEnum;
import com.jzo2o.market.model.domain.Activity;
import com.jzo2o.market.service.IActivityService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class PreHeatJob {
    @Resource
    private IActivityService activityService;
    @Resource
    private RedisTemplate redisTemplate;

    @Scheduled(cron = "0 0/1 * * * ?")
    public void preHeat() {
        log.info("开始执行优惠券预热任务");
        // 查询符合条件的 优惠券活动  :  状态在待生效
        List<Activity> activityList = activityService.list(Wrappers.<Activity>lambdaQuery()
                .eq(Activity::getStatus, ActivityStatusEnum.NO_DISTRIBUTE.getStatus()));
        if (activityList.isEmpty()) {
            log.info("没有需要预热的优惠券");
            return;
        }
        //存入redis
       log.info("开始将优惠券库存存入redis");
        for (Activity activity : activityList) {
            Integer stockNum = activity.getStockNum();
            //过期时间
            LocalDateTime expireTime = activity.getDistributeEndTime().plusDays(1);
            long millis = Duration.between(LocalDateTime.now(), expireTime).toMillis();
            redisTemplate.opsForValue().set(RedisConstants.RedisKey.COUPON_RESOURCE_STOCK+activity.getId(), stockNum,millis, TimeUnit.MINUTES);
        }


    }
}
